package com.xjzd.std.concurrency;

import java.util.concurrent.Semaphore;

public class AlternatePrintingWithSemaphore {
    private static final Semaphore semaphore1 = new Semaphore(1);
    private static final Semaphore semaphore2 = new Semaphore(0);
    private static int number = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                try {
                    semaphore1.acquire();
                    System.out.println("Thread 1: " + number++);
                    semaphore2.release();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                try {
                    semaphore2.acquire();
                    System.out.println("Thread 2: " + number++);
                    semaphore1.release();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}